package com.simon.jkxj.ui.diagnostic

import android.Manifest
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.Button
import android.widget.ProgressBar
import android.widget.RadioGroup
import android.widget.TextView
import android.widget.RadioButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.simon.jkxj.R
import com.simon.jkxj.model.ConstitutionResult
import com.simon.jkxj.model.ConstitutionResults
import com.simon.jkxj.model.DiagnosticQuestion
import com.simon.jkxj.model.DiagnosticQuestions
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class DiagnosticActivity : AppCompatActivity() {

    private lateinit var faceDiagnosisLayout: ConstraintLayout
    private lateinit var consultationLayout: ConstraintLayout
    private lateinit var diagnosisResultLayout: ConstraintLayout
    private lateinit var loadingProgressBar: ProgressBar
    
    private var currentPage = 0 // 0: 面诊, 1: 问诊, 2: 诊断结果
    private var currentQuestionIndex = 0
    private val answers = mutableListOf<Int>()
    private var photoFile: File? = null
    
    companion object {
        private const val CAMERA_PERMISSION_REQUEST = 100
        private const val CAMERA_REQUEST = 101
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_diagnostic)
        
        initViews()
        setupListeners()
        
        // 默认显示面诊页面
        showPage(0)
    }
    
    private fun initViews() {
        // 初始化布局
        faceDiagnosisLayout = findViewById(R.id.layout_face_diagnosis)
        consultationLayout = findViewById(R.id.layout_consultation)
        diagnosisResultLayout = findViewById(R.id.layout_diagnosis_result)
        loadingProgressBar = findViewById(R.id.loading_progress)
        
        // 初始化工具栏
        val toolbar = findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowTitleEnabled(false)
    }
    
    private fun setupListeners() {
        // 工具栏返回按钮
        findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbar)?.setNavigationOnClickListener {
            onBackPressed()
        }
        
        // 面诊页面 - 拍照按钮
        findViewById<androidx.appcompat.widget.AppCompatButton>(R.id.btn_start_photo).setOnClickListener {
            animateButtonClick(it)
            checkCameraPermissionAndOpen()
        }
        
        // 面诊页面 - 相册选择按钮
        findViewById<androidx.appcompat.widget.AppCompatButton>(R.id.btn_pick_photo).setOnClickListener {
            animateButtonClick(it)
            openGallery()
        }
        
        // 问诊页面 - 下一题按钮
        findViewById<Button>(R.id.btn_next).setOnClickListener {
            if (currentQuestionIndex < DiagnosticQuestions.questions.size - 1) {
                val selectedId = findViewById<RadioGroup>(R.id.rg_options).checkedRadioButtonId
                if (selectedId != -1) {
                    val selectedIndex = when (selectedId) {
                        R.id.rb_option_1 -> 0
                        R.id.rb_option_2 -> 1
                        R.id.rb_option_3 -> 2
                        R.id.rb_option_4 -> 3
                        else -> -1
                    }
                    if (selectedIndex != -1) {
                        answers.add(selectedIndex)
                        currentQuestionIndex++
                        showQuestion(currentQuestionIndex)
                    }
                }
            } else {
                // 最后一题，显示结果
                showLoading()
                it.postDelayed({
                    hideLoading()
                    showRandomResult()
                }, 1500)
            }
        }
    }
    
    private fun checkCameraPermissionAndOpen() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                arrayOf(Manifest.permission.CAMERA),
                CAMERA_PERMISSION_REQUEST)
        } else {
            openCamera()
        }
    }
    
    private fun openCamera() {
        try {
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            photoFile = createImageFile()
            photoFile?.let { file ->
                val photoURI = FileProvider.getUriForFile(this,
                    "${packageName}.provider",
                    file)
                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                startActivityForResult(intent, CAMERA_REQUEST)
            } ?: run {
                Toast.makeText(this, "无法创建临时文件", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Toast.makeText(this, "打开相机失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun openGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, CAMERA_REQUEST)
    }
    
    private fun createImageFile(): File? {
        return try {
            val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
            val storageDir = getExternalFilesDir(null)
            File.createTempFile(
                "JPEG_${timeStamp}_",
                ".jpg",
                storageDir
            )
        } catch (e: Exception) {
            null
        }
    }
    
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == CAMERA_PERMISSION_REQUEST) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openCamera()
            } else {
                Toast.makeText(this, "需要相机权限才能进行拍照", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == CAMERA_REQUEST) {
            when (resultCode) {
                RESULT_OK -> {
                    photoFile?.let {
                        if (it.exists() && it.length() > 0) {
                            navigateToConsultation()
                        } else {
                            Toast.makeText(this, "拍照失败，请重试", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
                RESULT_CANCELED -> {
                    Toast.makeText(this, "已取消拍照", Toast.LENGTH_SHORT).show()
                    // 清理未使用的临时文件
                    photoFile?.delete()
                }
                else -> {
                    Toast.makeText(this, "拍照失败，请重试", Toast.LENGTH_SHORT).show()
                    photoFile?.delete()
                }
            }
        }
    }
    
    private fun showQuestion(index: Int) {
        val question = DiagnosticQuestions.questions[index]
        findViewById<TextView>(R.id.tv_question).text = question.question
        
        // 设置选项
        findViewById<RadioButton>(R.id.rb_option_1).text = question.options[0]
        findViewById<RadioButton>(R.id.rb_option_2).text = question.options[1]
        findViewById<RadioButton>(R.id.rb_option_3).text = question.options[2]
        findViewById<RadioButton>(R.id.rb_option_4).text = question.options[3]
        
        // 清除选择
        findViewById<RadioGroup>(R.id.rg_options).clearCheck()
        
        // 更新进度
        findViewById<TextView>(R.id.tv_progress).text = "${index + 1}/30"
    }
    
    private fun showRandomResult() {
        val randomResult = ConstitutionResults.results.random()
        findViewById<TextView>(R.id.tv_constitution_type).text = randomResult.type
        findViewById<TextView>(R.id.tv_description).text = randomResult.description
        
        // 显示具体表现
        val manifestationsText = randomResult.manifestations.joinToString("\n")
        findViewById<TextView>(R.id.tv_manifestations).text = manifestationsText
        
        // 显示建议
        val suggestionsText = randomResult.suggestions.joinToString("\n")
        findViewById<TextView>(R.id.tv_suggestions).text = suggestionsText
        
        showPage(2)
    }
    
    private fun showPage(pageIndex: Int) {
        currentPage = pageIndex
        faceDiagnosisLayout.visibility = if (pageIndex == 0) View.VISIBLE else View.GONE
        consultationLayout.visibility = if (pageIndex == 1) View.VISIBLE else View.GONE
        diagnosisResultLayout.visibility = if (pageIndex == 2) View.VISIBLE else View.GONE
        
        if (pageIndex == 1) {
            showQuestion(0)
        }
    }
    
    private fun showLoading() {
        loadingProgressBar.visibility = View.VISIBLE
    }
    
    private fun hideLoading() {
        loadingProgressBar.visibility = View.GONE
    }
    
    private fun animateButtonClick(view: View) {
        val scaleDown = ObjectAnimator.ofFloat(view, "scaleX", 1f, 0.95f)
        scaleDown.duration = 100
        scaleDown.interpolator = AccelerateDecelerateInterpolator()
        
        val scaleUp = ObjectAnimator.ofFloat(view, "scaleX", 0.95f, 1f)
        scaleUp.duration = 100
        scaleUp.interpolator = AccelerateDecelerateInterpolator()
        
        scaleDown.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                scaleUp.start()
            }
        })
        
        scaleDown.start()
        
        // 同时缩放Y轴
        val scaleDownY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 0.95f)
        scaleDownY.duration = 100
        scaleDownY.interpolator = AccelerateDecelerateInterpolator()
        
        val scaleUpY = ObjectAnimator.ofFloat(view, "scaleY", 0.95f, 1f)
        scaleUpY.duration = 100
        scaleUpY.interpolator = AccelerateDecelerateInterpolator()
        
        scaleDownY.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                scaleUpY.start()
            }
        })
        
        scaleDownY.start()
    }
    
    private fun navigateToConsultation() {
        showPage(1)
    }
    
    override fun onBackPressed() {
        when (currentPage) {
            1 -> { // 从问诊页面返回面诊页面
                showPage(0)
                return
            }
            2 -> { // 从结果页面返回问诊页面
                showPage(1)
                return
            }
        }
        super.onBackPressed()
        // 使用自定义过渡动画
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right)
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 清理临时文件
        photoFile?.delete()
    }
} 